package cn.com.taiji.learn.sshelloworld.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author zouRiRi
 * @create 2021/3/8/15:36
 */
@Configuration
public class SecunityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
                .withUser("zouRiRi")
                .password(passwordEncoder().encode("19981230"))
                .roles("USER")
            .and().withUser("zouRiYang")
                .password(passwordEncoder().encode("19981230"))
                .roles("ADMIN");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * "/user/test/bar"这个可以不用登录访问
     * 设置特定页面只能特定用户访问
     * 其他的要登录访问
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/user/test/bar").permitAll()
                .antMatchers("/user/test/only-zouRiRi").hasRole("USER")
                .antMatchers("/user/test/foo").hasRole("ADMIN")
                .anyRequest().authenticated();
        http.formLogin()
        .loginPage("/login").permitAll()
        .loginProcessingUrl("/doLogin");

        http.logout().permitAll().logoutUrl("/logout");
        http.csrf().disable();
    }

    /**
     * ...下的不保护
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/images/**","/css/**","/js/**","/favicon/**");
    }
}
